<?php
function loadXML($path) {
	$dom = new DOMDocument;
	$dom->resolveExternals = true;
	$dom->load($path);
	if (!$dom) {
    		echo 'Error while parsing the document';
    		exit;
	}
	return $dom;
}

$mapFile = '../DITA-OT/samples/temp.ditamap';
$map = loadXML($mapFile);
$mapRoot = dirname($mapFile);
$s = simplexml_import_dom($map);
echo "<a href='?node='>" . $s['title'] . "</a>";
echo "<pre>";
function openChildren($s) {
	global $mapRoot;
	$s2 = false;
	$title = false;
	$id = "/s/workspace:SpacesStore/i/" . $id . "/children";
	$cmisid =  "/s/workspace:SpacesStore/i/" . $id;
	$leaf =  ($nodeType == "document")?true:false;
	$cls = ($nodeType == "document")?'document':'folder';	
	$text = '';

	
	foreach ($s->children() as $key1=>$val1) {
		switch (true) {
			case preg_match("/ mapgroup-d\/topichead /",$val1['class'])://topichead
				$node['text'] = $val1['navtitle'];
				$node['leaf'] =  false;
				$node['cls'] = 'folder';
				break;
			case preg_match("/ map\/topicref /",$val1['class']) and preg_match("/\.ditamap/",$val1['href'])://topicref to map
				$doc = simplexml_import_dom(loadXML($mapRoot . '/' . $val1['href']));
				$title = $doc->xpath('//*[contains(@class, " map/map ")][1]/*[contains(@class, " topic/title ")][1]/text()');
				if (empty($title)) {
					$title = $doc->xpath('//*[contains(@class, " map/map ")][1]/@title');
				}
				$node['id'] = "/s/workspace:SpacesStore/i/" . $id . "/children";
				$node['text'] = $title;
				$node['cmisid'] =  "/s/workspace:SpacesStore/i/" . $id;
				$node['href'] = $val1['href'];
				$node['leaf'] =  ($nodeType == "document")?true:false;
				$node['cls'] = 'folder';
				$mapFile = $mapRoot . '/' . $val1['href'];
				$map = loadXML($mapFile);
				$s2 = simplexml_import_dom($map);
				break;
			case preg_match("/ map\/topicref /",$val1['class']) and preg_match("/\.xml/",$val1['href'])://topicref to topic
				$doc = simplexml_import_dom(loadXML($mapRoot . '/' . $val1['href']));
				$title = $doc->xpath('//*[contains(@class, " topic/topic ")][1]/*[contains(@class, " topic/title ")][1]/text()');
				$node['id'] = "/s/workspace:SpacesStore/i/" . $id . "/children";
				$node['text'] = $title;
				$node['cmisid'] =  "/s/workspace:SpacesStore/i/" . $id;
				$node['href'] = $val1['href'];
				$node['leaf'] =  ($nodeType == "document")?true:false;
				$node['cls'] = 'document';
				break;
		}
		$nodes[] = $node;	
		echo "<li>" . $title[0] . " ( " . $href . " ) :" . $type;
		echo "<ul>";
		if ($s2) {
			openChildren($s2);
		}
		openChildren($val1);
		echo "</ul>";
		echo "</li>";
		return $nodes;
	}
}
echo "<ul>";

echo openChildren($s);

echo "</ul>";
//echo json_encode($s);

